import {mapGetters, mapMutations, mapActions} from 'vuex';
import {playMode} from 'common/js/config.js';
import {shuffle} from 'common/js/util.js';

export const playlistMixin = {
  computed: {
    ...mapGetters([
      'playList'
    ])
  },
  mounted () {
    this.handlePlaylistAction(this.playList);
  },
  activated () {
    this.handlePlaylistAction(this.playList);
  },
  watch: {
    playList (newVal) {
      this.handlePlaylistAction(newVal);
    }
  },
  methods: {
    handlePlaylistAction () {
      throw new Error('component must implement handlePlaylistAction method');
    }
  }
};
export const playerMixin = {
  computed: {
    modeIcon () {
      return this.mode === playMode.sequence ? 'icon-sequence' : this.mode === playMode.loop ? 'icon-loop' : 'icon-random';
    },
    ...mapGetters([
      'playList',
      'sequenceList',
      'currentSong',
      'favoriteList',
      'mode'
    ])
  },
  methods: {
    changeMode () {
      this.setPlayMode((this.mode + 1) % 3);
      let list = null;
      if (this.mode === playMode.random) {
        list = shuffle(this.sequenceList);
      } else {
        list = this.sequenceList;
      }
      this.resetCurrentIndex(list);
      this.setPlayList(list);
    },
    resetCurrentIndex (list) {
      let index = list.findIndex(item => {
        return item.id === this.currentSong.id;
      });
      this.setSongIndex(index);
    },
    getFavoriteIcon (item) {
      if (this.isFavorite(item)) {
        return 'icon-favorite';
      }
      return 'icon-not-favorite';
    },
    toggleFavorite (item) {
      if (this.isFavorite(item)) {
        this.deleteFavoriteList(item);
      } else {
        this.saveFavoriteList(item);
      }
    },

    isFavorite (song) {
      const index = this.favoriteList.findIndex((item) => {
        return item.id === song.id;
      });
      return index > -1;
    },
    ...mapMutations({
      setPlayingState: 'SET_PLAYING_STATE',
      setSongIndex: 'SET_CURRENT_INDEX',
      setPlayMode: 'SET_PLAY_MODE',
      setPlayList: 'SET_PLAYLIST'
    }),
    ...mapActions([
      'saveFavoriteList',
      'deleteFavoriteList'
    ])
  }
};

export const searchMixin = {
  data () {
    return {
      query: ''
    };
  },
  computed: {
    ...mapGetters([
      'searchHistory'
    ])
  },
  methods: {
    blurInput () {
      this.$refs.serachBox.blurInput();
    },
    onQueryChange (q) {
      this.query = q;
    },
    addQuery (v) {
      this.$refs.serachBox.setQuery(v);
    },
    saveSearch () {
      this.saveSearchHistory(this.query);
    },
    deleteOneSearchHistory (item) {
      this.deleteSearchHistory(item);
    },
    ...mapActions([
      'saveSearchHistory',
      'deleteSearchHistory'
    ])
  }
};
